package com.zbu.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zbu.reggie.common.R;
import com.zbu.reggie.config.Log;
import com.zbu.reggie.dto.DishDto;
import com.zbu.reggie.entity.Category;
import com.zbu.reggie.entity.Dish;
import com.zbu.reggie.entity.DishFlavor;
import com.zbu.reggie.service.CategoryService;
import com.zbu.reggie.service.DishFlavorService;
import com.zbu.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /*新增菜品*/
    @PostMapping
    @Log
    public R<String> save(@RequestBody DishDto dishDto) {//页面提交的JSON数据 要加上RequestBody
        log.info("disDto:{}", dishDto);
        //自定义方法 实现新增菜品，同时插入菜品对应的口味数据 操作两个表 dish dish_flavor
        dishService.saveWithFlavor(dishDto);
        //获取所有key并且清除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("新增菜品成功");
    }

    /*
     * 菜品信息分页查询*/
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page:{},pageSize:{},name:{}", page, pageSize, name);
        //分页构造器
        //Dish没有categoryName这个属性 所以不会显示分类名称
        Page<Dish> pageinfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);//目前dishDtoPage是空的 没有赋值
        //条件构造器
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Dish::getName, name);
        //排序条件
        wrapper.orderByDesc(Dish::getUpdateTime);
        //执行查询
        dishService.page(pageinfo, wrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageinfo, dishDtoPage, "records");//第三个变量：不拷贝的属性

        List<Dish> records = pageinfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);

            return dishDto;
        }).toList();

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /*根据id查询
    菜品信息及对应的口味信息 实现回写*/
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }


    /*修改菜品*/
    @PutMapping
    @Log
    public R<String> update(@RequestBody DishDto dishDto) {//页面提交的JSON数据 要加上RequestBody
        log.info("disDto:{}", dishDto);
        //自定义方法 实现新增菜品，同时更新菜品对应的口味数据 操作两个表 dish dish_flavor
        dishService.updateWithFlavor(dishDto);
        //获取所有key并且清除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("修改菜品成功");
    }

    /*根据条件查询对应的菜品数据
     在套餐管理的添加套餐里面*/
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList = null;

        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //1.从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //2.如果存在 直接返回 不需要查询数据库
        if (dishDtoList != null) {
            return R.success(dishDtoList);
        }

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        //3.不存在 查询数据库 并且缓存到redis中
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }


    //停售 起售
    @PostMapping("/status/{status}")
    @Log
    public R<String> updates(@PathVariable Integer status,
                             @RequestParam List<Long> ids) {
        log.info("批量起售或停售 菜品");
        LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(Dish::getId, ids);
        wrapper.set(Dish::getStatus, status);
        dishService.update(wrapper);
        //获取所有key并且清除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("修改成功");
    }

    /*删除菜品
     * 批量删除*/
    @DeleteMapping
    @Log
    public R<String> remove(@RequestParam List<Long> ids) {
        log.info("删除菜品的id:{}", ids);
        dishService.removeByIds(ids);
        //获取所有key并且清除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("删除菜品成功");
    }

}
